package com.hospital.pet.love.lovepethospital.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.pet.love.lovepethospital.domain.User;
import com.hospital.pet.love.lovepethospital.dto.user.UserDto;
import com.hospital.pet.love.lovepethospital.exp.ShawCustomException;
import com.hospital.pet.love.lovepethospital.mapper.EmployeeMapper;
import com.hospital.pet.love.lovepethospital.resp.ResultCodeEnum;
import com.hospital.pet.love.lovepethospital.service.UserService;
import com.hospital.pet.love.lovepethospital.mapper.UserMapper;
import com.hospital.pet.love.lovepethospital.util.AuthenticationContextUtil;
import com.hospital.pet.love.lovepethospital.vo.user.LoginVo;
import com.hospital.pet.love.lovepethospital.vo.user.UserInfoVo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author RoselleShaw
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-04-19 11:05:11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public LoginVo login(UserDto userDto) {

        if (StrUtil.isEmpty(userDto.getPhone()) || StrUtil.isEmpty(userDto.getPassword())) {
            throw new ShawCustomException(ResultCodeEnum.PHONE_PASSWORD_NULL);
        }

        // 查询用户，不存在抛出异常
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, userDto.getPhone())
                .eq(User::getPassword, DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes())));
        if (user == null) {
            throw new ShawCustomException(ResultCodeEnum.LOGIN_ERROR);
        }

        LoginVo loginVo = new LoginVo();

        // 登录成功，保存 token
        String token = IdUtil.simpleUUID();
        loginVo.setToken(token);
        stringRedisTemplate.opsForValue().set(
                "user:login" + token,
                JSON.toJSONString(user),
                1,
                TimeUnit.HOURS
        );

        return loginVo;
    }

    @Override
    public void register(UserDto userDto) {
        if (StrUtil.isEmpty(userDto.getPhone()) || StrUtil.isEmpty(userDto.getPassword())) {
            throw new ShawCustomException(ResultCodeEnum.PHONE_PASSWORD_NULL);
        }
        if (userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, userDto.getPhone())) != null) {
            throw new ShawCustomException(ResultCodeEnum.PHONE_EXIST);
        }
        User user = new User();
        user.setPhone(userDto.getPhone());
        user.setPassword(DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes()));
        user.setRole("客户");
        userMapper.insert(user);
    }

    @Override
    public void logout(String token) {
        stringRedisTemplate.delete(token);
    }

    @Override
    public void changePassword(String password) {
        if (StrUtil.isEmpty(password)) {
            throw new ShawCustomException(ResultCodeEnum.CHANGE_PASSWORD_ERROR);
        }
        User user = AuthenticationContextUtil.get();
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userMapper.updateById(user);
    }

    @Override
    public UserInfoVo getUserInfo() {
        User user = AuthenticationContextUtil.get();
        UserInfoVo userInfoVo = new UserInfoVo();
        if ("员工".equals(user.getRole())) {
            String job = employeeMapper.getByPhone(user.getPhone());
            userInfoVo.setJob(job);
        }
        userInfoVo.setPhone(user.getPhone());
        userInfoVo.setPassword(user.getPassword());
        userInfoVo.setRole(user.getRole());
        return userInfoVo;
    }
}




